<template>
  <el-dialog
    title="人员头像拍摄"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="dialogClose" ref="dialog">
    <el-row>
      <el-col :span="12">
        <el-row>
          <div class="video-view">
            <video ref="video" v-if="showVedio" width="300" height="300"></video>
            <span class="video vedio-tip" v-else>摄像头已关闭</span>
          </div>
        </el-row>
      </el-col>
      <el-col :span="12">
        <el-row>
          <el-col :span="12">
            <div class="idcard-veryfy">
              <div class="canvas-img-box">
                <canvas class="" ref="snapCanvas" width="300" height="300" v-show="false"></canvas>
                <img  :src="base64Tophoto(photoImg)" style="height:300px;width:300px;">
              </div>
            </div>
          </el-col>
          <el-button type="success" round  @click="tackPhoto" style="width:300px;margin-top:15px;">拍照</el-button>
          </el-row>

      </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">{{ $t('handle.cancel') }}</el-button>
        <el-button type="primary"  @click="dataFormSubmit()">{{ $t('handle.confirm') }}</el-button>
      </span>
  </el-dialog>
</template>

<script>
  import { validatenull } from '@/utils/validate'
  import { imgUrlHost } from '@/config/env'
  export default {
    components: {

    },
    data() {
      return {
        mediaStream: null, // 视频流
        stop: true,
        imgUrlHost: imgUrlHost,
        photoImg: '',
        showVedio: true,
        visible: false,
        snapData: '', // 拍照图片数据
        callValue: {}, // 回传给父组件的拼装的值
      }
    },
    computed: {
      base64Tophoto(){
        return function(photo){
          if(photo === ''){
            return require("@/assets/img/idcard/snap-default.png")
          }else {
             return this.imgUrlHost + photo
          }
        }
      }
    },
    created() {
      // this.playVideo()
    },
    beforeDestroy() {
     this.stopCamera()
    },
    methods: {
      // 组件初始化
      init (){
        this.visible = true
        this.photoImg = ''
        this.openCamera()
      },
      // 组件关闭
      dialogClose(){
        // 清空数据
        this.snapData = ''// 拍照图片数据
        this.idCardInfo = {}
        this.callValue = {} // 回传给父组件的拼装的值
        this.formData = {} // 对比记录，提交表单用
        this.score = 0 // 匹配得分
        // 关闭摄像头
        this.stopCamera()
      },
      // 打开摄像头播放视频
      playVideo(){
        let con = {
          audio:false,
          video:{
            width: 300,
            height: 300
          }
        }
        this.$nextTick(() => {
          /********************************兼容老的浏览器开始*************************/
          if (navigator.mediaDevices === undefined) {
            navigator.mediaDevices = {};
          }
          if (navigator.mediaDevices.getUserMedia === undefined) {
            navigator.mediaDevices.getUserMedia = function(constraints) {
              // 如果有getUserMedia,就获得它
              let getUserMedia = navigator.getUserMedia ||
                                navigator.webkitGetUserMedia ||
                                navigator.mozGetUserMedia ||
                                navigator.msGetUserMedia;
              // 浏览器没实现这个api，返回reject
              if (!getUserMedia) {
                return Promise.reject(new Error('当前浏览器不支持打开摄像头'));
              }
              // 封装navigator.getUserMedia为promis,保持接口统一
              return new Promise(function(resolve, reject) {
                getUserMedia.call(navigator, constraints, resolve, reject);
              });
            }
          }
          /********************************兼容老的浏览器结束*************************/
          // 播放视频（最新h5API）
          navigator.mediaDevices.getUserMedia(con).then( mediaStream => {
             this.mediaStream = mediaStream
            // 旧的浏览器可能没有srcObject
            if ("srcObject" in this.$refs.video){
               this.$refs.video.srcObject = mediaStream
            } else {
               this.$refs.video.src = window.URL.createObjectURL(stream);
            }
            this.$refs.video.play()
          }, error => {
            console.log("打开摄像头失败",error)
            this.showVedio = false
            this.cameraTip = "摄像头打开失败（点击重试）"
            this.$message.error("打开摄像头失败")
          });
        })
      },
      dataFormSubmit() {
        if(this.photoImg === ''){
          this.$message.error('请先拍照！');
          return
        }
        this.visible = false;
        this.$emit("verifyResult",this.photoImg);
        // this.$http({
        //   url: `/dg-ic/ic/file/upload/base64`,
        //   method: 'post',
        //   data:{
        //     photo: this.snapData
        //   }
        // }).then( res => {
        //   if (res.data && res.data.code === 0) {
        //     this.$message({
        //       message: "操作成功",
        //       type: "success",
        //       duration: 1500,
        //       onClose: () => {
        //         this.visible = false;
        //         this.$emit("verifyResult",res.data.data);
        //       }
        //     });
        //   } else {
        //     this.$message.error(data.msg);
        //   }
        // })
      },
      // 拍照
      tackPhoto(){
        this.$refs.snapCanvas.getContext("2d").drawImage(this.$refs.video, 0, 0, 300, 300)
        this.getBase64()
        //  this.getIdCardInfo()
      },
      // 关闭摄像头
      stopCamera(){
        if(this.mediaStream != null){
          this.showVedio = false
          this.mediaStream.getTracks()[0].stop()
        }
      },
      // 开启摄像头
      openCamera(){
        this.showVedio = true
        this.playVideo()
      },
      // 获取抓拍图片base64上传到文件服务器上
      getBase64(){
        let imgSrc = this.$refs.snapCanvas.toDataURL("image/png", 1)
        this.snapData = imgSrc.split("base64,")[1]
        this.$http({
          url: `/dg-ic/ic/file/upload/base64`,
          method: 'post',
          data:{
            photo: this.snapData
          }
        }).then( res => {
          if (res.data && res.data.code === 0) {
            this.photoImg = res.data.data.iconName
          } else {
            this.$message.error(data.msg);
          }
        })
      },
      // 传值给父组件
      callTheValue(){
        this.$emit("verifyResult", this.callValue)
      }
    }
  };
</script>

<style lang="scss" scoped>
  .video-view{
    width: 100%;
    height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 30px;
    .video{
      width:300px;
      height: 300px;
      border: 1px solid #f1f1f1;
    }
    .vedio-tip{
      font-size: 20px;
      color: #aaa;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .idcard-veryfy{
/*     display: flex;
    justify-content: center;
    align-items: center; */
    canvas{
      width: 105px;
      height: 130px;
      border: 1px solid #f1f1f1;
    }
    // .img-box{
    //   width: 227px;
    //   height: 300px;
    //   border: 1px solid #f1f1f1;
    // }
    .canvas-img-box{
      width: 300px;
      height: 300px;
      border: 1px solid #f1f1f1;
      img{
        max-height: 300px;
      }
    }

  }
</style>
